package developerworks.jetty6;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;

import developerworks.jetty6.*;


//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.SQLException;


//import com.mysql.*;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class UserServlet extends HttpServlet {
	public enum Method {PUT, POST, DELETE, GET}

	static private Connection conn;
	static public Pattern pattern = Pattern.compile("https?://(?:www\\.)?([^/]*)([^#\\?]*)");
	public void service(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		Timey t = new Timey();
		//if(! Jabbify.filterVersion(req, res)) return;
		
		res.setContentType("text/javascript");
		
		switch(method(req)){
			case PUT: update(req, res); break;
			case POST: create(req, res); break;
			case DELETE: destroy(req, res); break;
			case GET: list(req, res); break;
		}
	    
	    t.end("User");
	}
	public Method method(HttpServletRequest req){
		String method = req.getParameter("_method");
		if(method == null) method = req.getMethod();
		method = method.toLowerCase();
		if(method.compareTo("post") == 0) return Method.POST;
		if(method.compareTo("get") == 0) return Method.GET;
		if(method.compareTo("delete") == 0) return Method.DELETE;
		if(method.compareTo("put") == 0) return Method.PUT;
		return Method.POST;
	}
	public void destroy(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		HttpSession session = req.getSession(false);
		if(session != null){
			System.out.println("User:delete:"+session.getId());
			session.invalidate();
			String callback = req.getParameter("callback");
			res.getWriter().println(callback+"({session_id: '"+session.getId() +"'})" );
		}else{
			System.out.println("User:delete:?");
		}
		
		res.getWriter().flush();
		
	}
	public void showError(HttpServletRequest req){
		HttpSession session = req.getSession(false);
		System.out.println("  ua = "+req.getHeader("User-Agent"));
		if(session != null){
			System.out.println("  si = "+session.getId());
		}else{
			System.out.println("  si = ?");
		}
		System.out.println("  rf = "+req.getHeader("Referer"));	
		System.out.println("  ur = "+req.getRequestURL());
		System.out.println("  cb = "+req.getParameter("callback"));
		System.out.println("  id = "+req.getParameter("user[active_user_id]"));
		
		
	}
	
	
	public void list(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		String url = req.getHeader("Referer");
		System.out.println("GET called for "+url);
		res.getWriter().flush();
		//System.out.println("ERROR ----------------");
		//showError(req);
	}
	
	public void create(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		Timey t = new Timey();
		String url = req.getHeader("Referer");
		String name = req.getParameter("user[name]");
		String caller_id = req.getParameter("user[caller_id]");
		String hostname = System.getProperty("HOSTNAME");
		HttpSession session = req.getSession(true);

		if(session.isNew() && url != null){

			session.setMaxInactiveInterval(JabbifyServlet.TIMEOUT_SECS+45);
			String callback = req.getParameter("callback");
			
			String dn = "jabbify.com";
			Matcher matcher = pattern.matcher(req.getHeader("Referer"));
			boolean matchFound = matcher.find();
			if(matchFound){
				dn = matcher.group(1).toLowerCase();
			}else{
				System.out.println("Error parsing!!!!");
			}
			
			User u = new User(req, session);
			
			t.end("User_before");
			u.sendToDomain(dn);
			t.end("User_Sent");
			
			Inbox i = new Inbox(req,session, u);
			session.setAttribute("Inbox",i);
			ApplicationAddressBook.addInbox(i);
			t.end("User_Inbox");
			
			res.getWriter().println(callback+"({serv: '"+hostname+"', session_id: '"+session.getId()+"'})" );
			res.getWriter().flush();

		}else{
			System.out.println("THIS SHOULD NOT HAPPEN!!!!");
			res.getWriter().println("alert('THIS SHOULD NOT HAPPEN!!!!')" );
			res.getWriter().flush();
		}
		t.end("User_End");

		
	}
	public void update(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		HttpSession session = req.getSession(false);
		Inbox i = (Inbox) session.getAttribute("Inbox");
		String name = req.getParameter("user[name]");
		
		i.user.updateName(name);
		i.user.update();
		i.user.sendTo("@"+ApplicationAddressBook.getDomainName(req));
		
		String callback = req.getParameter("callback");
		res.getWriter().println(callback+"({session_id: '"+session.getId() +"'})" );
		res.getWriter().flush();
		
	}
	
	
	
	/*public Collection<Message> getMessages(){
		Connection conn = DBConnection.get();
		Collection<Message> messages = new ArrayList<Message>();
		
		try{
			Statement s = conn.createStatement ( );
			//AND messages.domain_id = 4
			s.executeQuery ("SELECT id, name, website, active_user_id, message FROM `messages` WHERE (messages.status = 'approved') ORDER BY messages.id DESC LIMIT 40");
			ResultSet rs = s.getResultSet ( );
			int count = 0;
			while (rs.next ( )) // loop through rows of result set
			{
				int id = rs.getInt (1);
				String name = rs.getString(2);
				String active_user_id = rs.getString(3);
				String message = rs.getString(4);
				++count;
				
				System.out.println (count + ",id: " + id + ",name: " +
				name + ",message: " + message);
			}
		}catch(Exception e){
			System.out.println(e.toString());
			
		}
		return messages;
	}*/
	
}
